/*
 * Copyright 2010 WANdisco, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */
package com.googlecode.svnj;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

import org.mortbay.jetty.Server;
import org.mortbay.jetty.webapp.WebAppContext;

import com.googlecode.svnj.dav.IO;

public class JettyMain {
    
    private final Server server;
    public JettyMain(String svnParentPath, int port) {
        // because of classloader visibility issues, notify
        // the guts of our desired svnParentPath via a system property 
        System.setProperty(IO.SYSPROP_PARENT_PATH, svnParentPath);
        final String WEBAPPDIR = "web";

        server = new Server(port);

        final String CONTEXTPATH = "";

        URL warUrl = JettyMain.class.getClassLoader().getResource(WEBAPPDIR);
        if (warUrl == null) {
            try {
                warUrl = new File(WEBAPPDIR).toURI().toURL();
            } catch (MalformedURLException mfe) {
                throw new RuntimeException(mfe);
            }
        }
        final String warUrlString = warUrl.toExternalForm();
        server.setHandler(new WebAppContext(warUrlString, CONTEXTPATH));

    }
    
    public void start() throws Exception {
        server.start();
    }
    
    public void stop() throws Exception {
        server.stop();
    }
    
    private static void error(String msg) {
        System.err.println(JettyMain.class.getSimpleName() + ": ERROR: " + msg);
        usage();
    }
    private static void usage() {
        System.err.println("usage: java " + JettyMain.class.getName() + " <svn-parent-path-directory> <listen-port>");
        System.exit(1);
    }
    public static void main(String[] args) throws Exception {
        // directory of web application (exploded war file)
        
        if (args.length != 2) {
            usage();
        }
        int port = -1;
        try {
            port = Integer.parseInt(args[1]);
        } catch (NumberFormatException nfe) {
            error("invalid port: '" + args[1] + "'");
            usage();
        }
        JettyMain jm = new JettyMain(args[0], port);
        jm.start();
    }
    
}
